<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>设备列表</h3>
        <div>
          <el-input
            v-model="searchImei"
            placeholder="请输入设备IMEI"
            style="width: 200px; margin-right: 10px;"
          />
          <el-button type="primary" @click="searchByImei">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button v-if="isFiltered" @click="resetSearch">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="$router.push('/devices/add')" style="margin-left: 10px;">
            <el-icon><Plus /></el-icon>
            添加设备
          </el-button>
        </div>
      </div>
      
      <el-table :data="devices" v-loading="loading" style="width: 100%">
        <el-table-column prop="deviceModel" label="设备型号" />
        <el-table-column prop="deviceImei" label="设备IMEI" />
        <el-table-column prop="deviceToken" label="设备Token" />
        <el-table-column prop="deviceRemark" label="设备备注" />
        <el-table-column prop="createdTime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="600" header-align="center" align="center" >
          <template #default="scope">
            <el-button size="small" @click="handleConfig(scope.row)">
              <el-icon><Setting /></el-icon>
              参数设置
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="warning" @click="handleReboot(scope.row)">
                          <el-icon><Warning /></el-icon>
                          重启
            </el-button>
            <el-button size="small" type="info" @click="handlePowerOff(scope.row)">
                          <el-icon><Warning /></el-icon>
                          关机
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshLeft, Plus, Edit, Delete, Setting, Warning, Monitor, SwitchButton } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'DeviceList',
  components: {
    Search, RefreshLeft, Plus, Edit, Delete, Setting, Warning, Monitor, SwitchButton
  },
  setup() {
    const router = useRouter()
    const devices = ref([])
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    const searchImei = ref('')
    const isFiltered = ref(false)
    
    const loadDevices = async () => {
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get('/api/devices', {
          headers: { Authorization: `Bearer ${token}` }
        })
        devices.value = response.data
      } catch (error) {
        ElMessage.error('加载设备列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleConfig = (device) => {
      router.push(`/devices/config/${device.deviceImei}`)
    }
    
    const handleEdit = (device) => {
      router.push(`/devices/edit/${device.id}`)
    }

    const handleReboot = (device) => {
          router.push(`/devices/reboot/${device.id}`)
    }

    const handlePowerOff = (device) => {
          router.push(`/devices/powerOff/${device.id}`)
    }
    
    const handleDelete = async (device) => {
      try {
        await ElMessageBox.confirm('确定要删除这个设备吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        await axios.delete(`/api/devices/${device.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        ElMessage.success('删除成功')
        loadDevices()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }
    
    const formatDate = (timestamp) => {
      if (!timestamp) return ''
      return new Date(timestamp).toLocaleString()
    }
    
    onMounted(() => {
      loadDevices()
    })
    
    // 根据IMEI搜索设备
    const searchByImei = async () => {
      try {
        if (!searchImei.value) {
          ElMessage.warning('请输入设备IMEI')
          return
        }
        
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/devices/by-imei/${searchImei.value}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data) {
          devices.value = [response.data]
          isFiltered.value = true
          ElMessage.success('查询成功')
        } else {
          ElMessage.warning('未找到对应设备')
          devices.value = []
        }
      } catch (error) {
        if (error.response && error.response.status === 404) {
          ElMessage.warning('未找到对应设备')
          devices.value = []
        } else {
          ElMessage.error('查询失败')
        }
      } finally {
        loading.value = false
      }
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchImei.value = ''
      isFiltered.value = false
      loadDevices()
    }
    
    return {
      devices,
      loading,
      username,
      searchImei,
      isFiltered,
      handleConfig,
      handleEdit,
      handleReboot,
      handlePowerOff,
      handleDelete,
      handleLogout,
      formatDate,
      searchByImei,
      resetSearch
    }
  }
}
</script> 